<?php
namespace Home\Controller;


use Common\Model\GoodsModel;
use Org\Util\Cart;
use Think\Controller;
use Common\Model\TypeAttrModel;


/**
 * 内容页管理控制器
 * Class IndexController
 * @package Home\Controller
 */
class ContentController extends Controller
{
	//首页
	public function index ()
	{
		$headConf = [
				'js'=>['list'],
				'css'=>['index'],
				'title'=>'上一天堂'
		];
		$this->assign('headConf',$headConf);
		$gid = I('get.gid');
//		p($gid);
		//获取当前商品相关数据
		$goodsData = (new GoodsModel())->alias('g')
			->join("sh_detail d on g.gid=d.gid")
			->where("g.gid=$gid")->find();
//		p($goodsData);
		//获取规格数据
		$data = (new TypeAttrModel())->alias('ta')
			->join("sh_goods_attr ga on ta.aid=ga.aid")
			->where("class=1 and ga.gid=$gid")->field('ga.aid,aname,gtid,gtvalue')->select();
		$temp = [];
		foreach($data as $k=>$v)
		{
			$temp[$v['aid']]['name'] = $v['aname'];
			$temp[$v['aid']]['value'][] = $v;
		}
//		p($temp);
		$this->assign('goodsData',$goodsData);
		$this->assign('specData',$temp);
		$this->display();
		//Request::session($this->cartName);
		  //$_SESSION[$this->cartName]
		//Request::session($this->cartName, $data);
			//$_SESSION[$this->cartName] = $data
	}
	//点击规格异步获取数据
	public function ajaxGetTotal(){
		//在货品列表中查找当前选择的规格对应的库存

		if(IS_AJAX)
		{
//			echo 123;die;
			$combine = rtrim($_POST['combine'],',');
//			p($combine);die;
			$gid = $_POST['gid'];

			$res = m('goods_list')->where("combine='{$combine}' and gid={$gid}")->find();
//			p($res);die;
			//如果找不到对应的数据，我们也视为没有库存
			if(!$res){
				$this->ajaxReturn(['valid'=>0,'inventory'=>0]);exit;
			}
			//找到数据，但是库存为0
			if($res['inventory']==0){
				$this->ajaxReturn(['valid'=>0,'inventory'=>0]);exit;
			}
			//找到数据，有库存
			$this->ajaxReturn(['valid'=>1,'inventory'=>$res['inventory']]);exit;
		}
	}
	/**
	 * 异步添加购物车
	 */
	public function ajaxAddCart()
	{
		if(IS_AJAX)
		{
			$gid = $_POST['gid'];//商品id
			$num = $_POST['num'];//购买数量
			$options = $_POST['options'];//购买的规格参数
			//根据商品id在商品表中查询
			$data = (new GoodsModel())->where("gid=$gid")->find();

			$data = [
					'id'        => $gid, // 商品 ID
					'name'      =>$data['gname'],// 商品名称
					'num'       => $num, // 商品数量
					'price'     => $data['shopprice'], // 商品价格
					'options'   => $options// 其他参数如价格、颜色、可以为数组或字符串
			];
			(new Cart())->add($data); // 添加到购物车
			echo 1;exit;
		}
	}

}